package org.mall.modules.shop.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.mall.common.api.vo.Result;
import org.mall.common.aspect.annotation.AutoLog;
import org.mall.common.system.query.QueryGenerator;
import org.mall.common.system.util.JwtUtil;
import org.mall.common.util.json.JacksonUtils;
import org.mall.common.util.oConvertUtils;
import org.mall.modules.pojo.shop.ShopCategoryVo;
import org.mall.modules.shop.entity.ShopCategory;
import org.mall.modules.shop.service.IShopCategoryService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: 商店条目管理
 * @Author: jeecg-boot
 * @Date:   2019-11-14
 * @Version: V1.0
 */
@Slf4j
@Api(tags="商店条目管理")
@RestController
@RequestMapping("/category")
public class ShopCategoryController {

	@Autowired
	private IShopCategoryService shopCategoryService;


	
	/**
	  * 分页列表查询
	 * @param goodsCategory
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "商店条目管理-分页列表查询")
	@ApiOperation(value="商店条目管理-分页列表查询", notes="商店条目管理-分页列表查询")
	@GetMapping(value = "/merchant/list")
	public Result<IPage<ShopCategory>> queryPageList(ShopCategory goodsCategory,
													 @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
													 @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
													 HttpServletRequest req) {
	    goodsCategory.setIsDeleted(0);
		Result<IPage<ShopCategory>> result = new Result<IPage<ShopCategory>>();
		QueryWrapper<ShopCategory> queryWrapper = QueryGenerator.initQueryWrapper(goodsCategory, req.getParameterMap());
		Page<ShopCategory> page = new Page<ShopCategory>(pageNo, pageSize);
		IPage<ShopCategory> pageList = shopCategoryService.page(page, queryWrapper);
		pageList.setRecords(pageList.getRecords().stream().sorted(Comparator.comparing(ShopCategory::getCategoryRank).reversed()).collect(Collectors.toList()));
		result.setSuccess(true);
		result.setResult(pageList);
		return result;
	}
	@GetMapping(value = "/app/list")
	public Result<IPage<ShopCategory>> queryPageListForMall(ShopCategory goodsCategory,
													 @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
													 @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
													 HttpServletRequest req) {
		goodsCategory.setIsDeleted(0);
		Result<IPage<ShopCategory>> result = new Result<IPage<ShopCategory>>();
		QueryWrapper<ShopCategory> queryWrapper = QueryGenerator.initQueryWrapper(goodsCategory, req.getParameterMap());
		Page<ShopCategory> page = new Page<ShopCategory>(pageNo, pageSize);
		IPage<ShopCategory> pageList = shopCategoryService.page(page, queryWrapper);
		pageList.setRecords(pageList.getRecords().stream().sorted(Comparator.comparing(ShopCategory::getCategoryRank).reversed()).collect(Collectors.toList()));
		result.setSuccess(true);
		result.setResult(pageList);
		return result;
	}
	/**
	  *   添加
	 * @param goodsCategoryVo
	 * @return
	 */
	@AutoLog(value = "商店条目管理-添加")
	@ApiOperation(value="商店条目管理-添加", notes="商店条目管理-添加")
	@PostMapping(value = "/merchant/add")
	public Result<?> add(@Valid @RequestBody ShopCategoryVo goodsCategoryVo, BindingResult bindingResult) {
		Result<ShopCategory> result = new Result<ShopCategory>();
		if (bindingResult.hasErrors()){
			return Result.error(JacksonUtils.toJSONString(bindingResult.getAllErrors()));
		}
		int num = shopCategoryService.queryCatogeryName(goodsCategoryVo.getCategoryName(),goodsCategoryVo.getShopId());
		if(num == 1){
			result.setMessage("该条目名已经存在！！");
			return result;
		}
		ShopCategory goodsCategory = new ShopCategory();
		BeanUtils.copyProperties(goodsCategoryVo,goodsCategory);
		goodsCategory.setCreateTime(new Date());
		goodsCategory.setCreateUser(JwtUtil.getUserIdByToken());
		//删除标识字段(0-未删除 1-已删除)
		goodsCategory.setIsDeleted(0);
		try {
            //根据商铺ID查询该商铺下所有条目排序最大值
			ShopCategory category = shopCategoryService.queryMaxForCategoryRank(goodsCategory.getShopId());
			//逻辑实现排序自增
			if(category == null){
				goodsCategory.setCategoryRank(1);
			}else{
				goodsCategory.setCategoryRank(category.getCategoryRank() + 1);
			}
            shopCategoryService.save(goodsCategory);
			result.success("添加成功！");
		} catch (Exception e) {
			log.error(e.getMessage(),e);
			result.error500("操作失败");
		}
		return result;
	}
	
	/**
	  *  编辑
	 * @param goodsCategoryVo
	 * @return
	 */
	@AutoLog(value = "商店条目管理-编辑")
	@ApiOperation(value="商店条目管理-编辑", notes="商店条目管理-编辑")
	@PostMapping(value = "/merchant/edit")
	public Result<?> edit(@Valid @RequestBody ShopCategoryVo goodsCategoryVo, BindingResult bindingResult) {
		Result<ShopCategory> result = new Result<ShopCategory>();
		if (bindingResult.hasErrors()){
			return Result.error(JacksonUtils.toJSONString(bindingResult.getAllErrors()));
		}
		ShopCategory goodsCategoryEntity = shopCategoryService.getById(goodsCategoryVo.getCategoryId());
		if(goodsCategoryEntity==null) {
			result.error500("未找到对应实体");
			return result;
		}
		ShopCategory goodsCategory = new ShopCategory();
		BeanUtils.copyProperties(goodsCategoryVo,goodsCategory);
		goodsCategory.setUpdateTime(new Date());
		goodsCategory.setUpdateUser(JwtUtil.getUserIdByToken());
		try{
			shopCategoryService.updateById(goodsCategory);
		}catch (Exception e){
			log.error("修改失败",e.getMessage());
			return Result.error("修改失败");
		}
		//TODO 返回false说明什么？
		return Result.ok("修改成功!");
	}
	
	/**
	  *   通过id删除
	 * @param goodsCategoryVo
	 * @return
	 */
	@AutoLog(value = "商店条目管理-通过id删除")
	@ApiOperation(value="商店条目管理-通过id删除", notes="商店条目管理-通过id删除")
	@PostMapping(value = "/merchant/delete")
	public Result<?> delete(@RequestBody ShopCategoryVo goodsCategoryVo) {
		if (goodsCategoryVo == null || StringUtils.isEmpty(goodsCategoryVo.getCategoryId())){
			return Result.error("条目ID不能为空！");
		}
		try {
			ShopCategory goodsCategory = new ShopCategory();
			BeanUtils.copyProperties(goodsCategoryVo,goodsCategory);
			shopCategoryService.deleteById(goodsCategory.getCategoryId());
			//删除条目关系表数据
			shopCategoryService.deleteCategoryRelationshipById(goodsCategory.getCategoryId());
		} catch (Exception e) {
			log.error("删除失败",e.getMessage());
			return Result.error("删除失败!");
		}
		return Result.ok("删除成功!");
	}
	
	/**
	  *  批量删除
	 * @param goodsCategory
	 * @return
	 */
	@AutoLog(value = "商店条目管理-批量删除")
	@ApiOperation(value="商店条目管理-批量删除", notes="商店条目管理-批量删除")
	@PostMapping(value = "/merchant/deleteBatch")
	public Result<?> deleteBatch(@RequestBody ShopCategory goodsCategory) {
		Result<ShopCategory> result = new Result<ShopCategory>();
		if(goodsCategory.getCategoryId() == null || "".equals(goodsCategory.getCategoryId().trim())) {
			result.error500("参数不识别！");
			return result;
		}
		try{
			this.shopCategoryService.deleteByIds(Arrays.asList(goodsCategory.getCategoryId().split(",")));
		}catch (Exception e){
			log.error("删除失败",e.getMessage());
			return Result.error("删除失败!");
		}
		return Result.ok("删除成功!");
	}
	
	/**
	  * 通过id查询
	 * @param id
	 * @return
	 */
	@AutoLog(value = "商店条目管理-通过id查询")
	@ApiOperation(value="商店条目管理-通过id查询", notes="商店条目管理-通过id查询")
	@GetMapping(value = "/merchant/queryById")
	public Result<ShopCategory> queryById(@RequestParam(name="id",required=true) String id) {
		Result<ShopCategory> result = new Result<ShopCategory>();
		ShopCategory goodsCategory = shopCategoryService.getById(id);
		if(goodsCategory==null) {
			result.error500("未找到对应实体");
		}else {
			result.setResult(goodsCategory);
			result.setSuccess(true);
		}
		return result;
	}

  /**
      * 导出excel
   *
   * @param request
   * @param response
   */
  @RequestMapping(value = "/merchant/exportXls")
  public ModelAndView exportXls(HttpServletRequest request, HttpServletResponse response) {
      // Step.1 组装查询条件
      QueryWrapper<ShopCategory> queryWrapper = null;
      try {
          String paramsStr = request.getParameter("paramsStr");
          if (oConvertUtils.isNotEmpty(paramsStr)) {
              String deString = URLDecoder.decode(paramsStr, "UTF-8");
              ShopCategory goodsCategory = JSON.parseObject(deString, ShopCategory.class);
              queryWrapper = QueryGenerator.initQueryWrapper(goodsCategory, request.getParameterMap());
          }
      } catch (UnsupportedEncodingException e) {
          e.printStackTrace();
      }

      //Step.2 AutoPoi 导出Excel
      ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
      List<ShopCategory> pageList = shopCategoryService.list(queryWrapper);
      //导出文件名称
      mv.addObject(NormalExcelConstants.FILE_NAME, "商店条目管理列表");
      mv.addObject(NormalExcelConstants.CLASS, ShopCategory.class);
      mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("商店条目管理列表数据", "导出人:Jeecg", "导出信息"));
      mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
      return mv;
  }

  /**
      * 通过excel导入数据
   *
   * @param request
   * @param response
   * @return
   */
  @RequestMapping(value = "/merchant/importExcel", method = RequestMethod.POST)
  public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
      MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
      Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
      for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
		  // 获取上传文件对象
          MultipartFile file = entity.getValue();
          ImportParams params = new ImportParams();
          params.setTitleRows(2);
          params.setHeadRows(1);
          params.setNeedSave(true);
          try {
              List<ShopCategory> listGoodsCategorys = ExcelImportUtil.importExcel(file.getInputStream(), ShopCategory.class, params);
              shopCategoryService.saveBatch(listGoodsCategorys);
              return Result.ok("文件导入成功！数据行数:" + listGoodsCategorys.size());
          } catch (Exception e) {
              log.error(e.getMessage(),e);
              return Result.error("文件导入失败:"+e.getMessage());
          } finally {
              try {
                  file.getInputStream().close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      }
      return Result.ok("文件导入失败！");
  }

    /**
     * 条目排序
     * @param list
     * @return
     */
     @PostMapping("/merchant/order")
     public Result<?> order(@RequestBody List<ShopCategoryVo> list){

         if (list.size()!=2){
             return Result.error("参数错误");
         }

         shopCategoryService.updateBatchById(list.stream().map(p->(new ShopCategory().setCategoryId(p.getCategoryId()).setCategoryRank(p.getCategoryRank())) )
                 .collect(Collectors.toList()));
         return Result.ok("更新成功");
     }
}
